package com.zj.web.controller;

import com.zj.service.UserService;
import com.zj.web.bean.MyUserDTO;
import com.zj.web.bean.ResponseResult;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * 轮播图控制器
 * */
@RestController
@RequestMapping("/auth")
@RefreshScope //开启动态刷新
@Tag(name = "用户控制器",description = "提供对用户资源的添加，查询并显示等操作")
public class AuthUserController {
    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 注册
     * 无需token 认证
     */
    @PostMapping("/register")
    @RefreshScope
    public ResponseEntity<ResponseResult> register( MyUserDTO myUserDTO){
        if (!verifyCode(myUserDTO.getUserName(), myUserDTO.getVerifyCode())) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                    .body(ResponseResult.error("验证码错误或已过期"));
        }

        MyUserDTO myUser =userService.register(myUserDTO);
        return ResponseEntity.status(HttpStatus.CREATED).body(ResponseResult.ok().setdata(myUser));
    }

    // 验证码验证逻辑（需自行实现）
    private boolean verifyCode(String username, String inputCode) {
        // 从Redis获取之前发送的验证码（例如：key=verify_code:{username}）
        String storedCode = redisTemplate.opsForValue().get("verify_code:" + username);
        return storedCode != null && storedCode.equals(inputCode);
    }

    /**
     * 检查用户名是否存在
     * 无需token 认证
     */
    @GetMapping("/checkUsername")
    public ResponseEntity<ResponseResult> checkUsername(@RequestParam("username") String username){
        boolean exists = userService.checkUsername(username);
        return ResponseEntity.status(HttpStatus.OK).body(ResponseResult.ok().setdata(exists?"用户名已存在"+username:"用户名可用"+username));
    }
    /**
     * 注销登录状态
     * 无需token 认证
     */
    @PostMapping("/logout")
    public ResponseEntity<ResponseResult> logout(){
        //TODO：注销登录状态(通常是客户端行为，服务端无状态)
        //对于无状态JWT 注销通常意味着客户端删除本地存储的token 或 失效时间设置短
        return ResponseEntity.status(HttpStatus.OK).body(ResponseResult.ok().setdata("注销成功"));
    }

    /**
     * 登录
     * 无需token 认证,登录后生成token并返回
     */
    @PostMapping("/login")  //RequestBody使用json字符串注入
    public ResponseEntity<ResponseResult> login(@RequestBody AuthRequest authRequest){
        AuthResponse authResponse = userService.login(authRequest);
//        System.out.println("登录成功，返回token: "+authResponse.toString());
        return ResponseEntity.status(HttpStatus.OK).body(ResponseResult.ok().setdata(authResponse));
    }

    @GetMapping("/sendVerifyCode/{username}")
    public ResponseEntity<ResponseResult> sendVerifyCode(@PathVariable("username") String username,
                                                         @RequestParam("email") String email) {
        MyUserDTO myUserDTO = userService.sendVerifyCode(username, email);
        if(myUserDTO!=null){
            return ResponseEntity.ok(ResponseResult.ok().setdata("验证码已发送"+myUserDTO.getVerifyCode()));
        }
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(ResponseResult.ok().setdata("验证码发送失败"));
    }

    /**
     * 批量生成用户
     */
    @PostMapping("/generateTestUsers/{count}")
    public ResponseEntity<ResponseResult> generateTestUsers(@PathVariable("count") int count) {
        generateTestUser(count);
        return ResponseEntity.status(HttpStatus.OK).body(ResponseResult.ok().setdata("成功创建"+count+"个测试用户"));
    }

    /**
     * 批量生成测试用户
     */
    public void generateTestUser(int count) {
        for (int i = 1; i <= count; i++) {
            try {
                MyUserDTO userDTO = new MyUserDTO();
                userDTO.setUserName("user" + System.currentTimeMillis() + i);
                userDTO.setUserPassword("123456"); // 统一密码
                userDTO.setPhone(generatePhone());
                userDTO.setEmail("3082311852@qq.com");
                userDTO.setGender((i % 3)); // 0,1,2 循环

                // 注册用户
                userService.register(userDTO);

                System.out.println("成功创建用户: " + userDTO.getUserName());

                // 避免过快调用，适当休眠
                Thread.sleep(100);

            } catch (Exception e) {
                System.out.println("创建用户失败: " + e.getMessage());
            }
        }
    }

    /**
     * 生成随机手机号
     */
    private String generatePhone() {
        Random random = new Random();
        return "13" + String.format("%09d", random.nextInt(1000000000));
    }

}
